import { _ } from 'meteor/underscore';
import { JoinClient } from 'meteor-publish-join';
import { clientChannelMembers } from '../../lib/collections';

Template.channel_members_panel.onCreated(function () {
  this.limit = new ReactiveVar(15);
  this.query = new ReactiveVar({});
  this.search = new ReactiveVar('');

  this.autorun(() => {
    const lmt = this.limit.get();
    const id = this.data.channel._id;
    this.query.set({
      channel_id: id,
      'user.username': {
        $regex: new RegExp(this.search.get())
      }
    });
    this.resultsSub = this.subscribe('get.channel.members', { id }, lmt);
    this.total = JoinClient.get('get.channel.members.counts');
  });
});

Template.channel_members_panel.onRendered(function() {
  const ps = new PerfectScrollbar('#channel-members-panel-content');

  $('#channel-members-panel-content').on('ps-y-reach-end', _.throttle(() => {
    let lmt = this.limit.get();
    if (this.total >= lmt) {
      this.limit.set(lmt + 15);
    }
  }, 200));
});

Template.channel_members_panel.helpers({
  results: function () {
    return clientChannelMembers.find(Template.instance().query.get(), {
      limit: Template.instance().limit.get(),
      sort: {
        createdAt: -1
      }
    });
  },

  loading: function () {
    return !Template.instance().resultsSub.ready();
  }
});

Template.channel_members_panel.events({
  'input #channel-members-panel-search' (e, instance) {
    let text = $.trim(e.target.value);
    instance.search.set(text);
  },

  'click #invite-member-button' (e, instance) {
    $('#invite-member-modal').modal();
  }
});